<template>
  <div>
    <!-- 轮播图 -->
    <el-card id="header">
      <el-carousel :interval="4000" type="card" height="200px">
        <el-carousel-item v-for="item in pictureList" :key="item.id">
          <img class="lunbo" :src="item.url" alt="">
        </el-carousel-item>
      </el-carousel>
    </el-card>
    <!-- 返回顶部 -->
    <div class="top">
      <el-button type="info" icon="el-icon-upload2" size="mini" @click="returnTop">顶部</el-button>
    </div>
    <!-- 搜索框 -->
    <div>
      <el-input v-model="goodsName" style="margin-left:60px;" placeholder="例如:物品名称,用户名等" class="select" clearable />
      <el-button round size="medium" icon="el-icon-search" style="margin-right:40px;" type="primary" @click="getGoodsBySelect(goodsName)">搜索</el-button>
      价格:<el-input v-model="minPrice" clearable placeholder="最低金额" class="money" @input="(v)=>(minPrice=v.replace(/[^\d.]/g,''))" /> ~ <el-input v-model="maxPrice" class="money" placeholder="最高金额" clearable @input="(v)=>(maxPrice=v.replace(/[^\d.]/g,''))" />
      <el-button round size="medium" style="margin-right:40px;" type="primary" @click="getGoodsByPrice(minPrice,maxPrice)">查询</el-button>
      排序:<el-button round size="mini" class="el-icon-caret-top" @click="GoodsPriceDesc" />
      <el-button round size="mini" class="el-icon-caret-bottom" @click="GoodsPriceEsc" />
    </div>
    <!-- 商品界面 -->
    <div v-if="goodsList.length <= 0">无法搜到数据，换个词试试吧~</div>
    <div v-else class="goods">
      <!-- eslint-disable-next-line vue/no-use-v-if-with-v-for -->
      <el-card v-for="(item, index) in goodsList" v-if="item.goodsOwner !== name " :key="item.goodsId">
        <!--后面优化，数量满了才出售完 || item.goodsCount < item.goodsNum -->
        <!-- 已卖完 -->
        <div v-if="item.goodsMessage === '已付款' || item.goodsMessage === '换购成功' " @click="queryGoodsId(item.goodsId)">
          <router-link :to=" {path:'/shopping/detai', query:{detaiGoodsId} }" target="_blank">
            <div>
              <span>
                <el-tag class="xuhao">{{ index }}</el-tag>
                物品:{{ item.goodsName }}
                发布者: {{ item.goodsOwner }}
                <hr>
                <img :src="item.goodsImg" alt="">
              </span>
              <hr>
              <div>描述:{{ item.goodsDesc }}</div>
              <span class="foot">
                价格:{{ item.goodsPrice.toFixed (2) }}
                数量:{{ item.goodsNum }}
              </span>
              <div class="kong">
                <el-tag>已经售空</el-tag>
              </div>
            </div>
          </router-link>
        </div>
        <!-- 换购中 -->
        <div v-else-if=" item.goodsMessage === '换购中'" @click="queryGoodsId(item.goodsId)">
          <router-link :to="{path:'/shopping/detai',query:{detaiGoodsId}}" target="_blank">
            <div>
              <span>
                <el-tag class="xuhao">{{ index }}</el-tag>
                物品:{{ item.goodsName }}
                发布者: {{ item.goodsOwner }}
                <hr>
                <img :src="item.goodsImg" alt="">
              </span>
              <hr>
              <div>描述:{{ item.goodsDesc }}</div>
              <span class="foot">
                价格:{{ item.goodsPrice.toFixed (2) }}
                数量:{{ item.goodsNum }}
              </span>
              <div class="kong">
                <el-tag>换购中</el-tag>
              </div>
            </div>
          </router-link>
        </div>
        <!--正常售卖-->
        <div v-else @click="queryGoodsId(item.goodsId)">
          <router-link :to="{path:'/shopping/detai',query:{detaiGoodsId}}" target="_blank">
            <span>
              <el-tag class="xuhao">{{ index }}</el-tag>
              物品:{{ item.goodsName }}
              发布者: {{ item.goodsOwner }}
              <hr>
              <img :src="item.goodsImg" alt="">
            </span>
            <hr>
            <div>描述:{{ item.goodsDesc }}</div>
          </router-link>
          <span class="foot">
            价格:{{ item.goodsPrice.toFixed (2) }}
            数量:{{ item.goodsNum }}
            <el-button class="btn-cart" icon="el-icon-plus" plain @click="addGoodsInCart(index)">购物车</el-button>
          </span>

        </div>
      </el-card>
    </div>

    <!-- 购物车图标 -->
    <div class="cart">
      <el-dropdown>
        <el-button v-if="count === 0" class="btn-buy" icon="el-icon-goods" type="primary" plain @click="open">
          <i class="sum">{{ count }}</i>
        </el-button>
        <el-button v-else class="btn-buy" icon="el-icon-goods" type="primary" @click="handle">
          <i class="sum">{{ count }}</i>
        </el-button>
        <el-dropdown-menu v-if="count != 0 " slot="dropdown" class="buyitem">
          <!-- eslint-disable-next-line vue/no-use-v-if-with-v-for -->
          <el-card v-for="(item, index) in cartList" v-if="item.goodsBuyer === name && item.goodsFlag === 0 " :key="item.goodsId">
            <img class="cart-img" :src="item.goodsImg" alt="">
            <el-tag>{{ index }}</el-tag>
            <el-tag>物品:{{ item.goodsName }}</el-tag>
            <el-tag>发布者:{{ item.goodsOwner }}</el-tag>
            <el-tag>价格:{{ item.goodsPrice.toFixed (2) }} * {{ item.goodsCount }}</el-tag>
            <el-tag>总数: {{ item.goodsNum }}
              <el-input-number v-model="item.goodsCount " :min="1" :max="item.goodsNum" size="mini" @change="changebtn" />
            </el-tag>
            <el-button type="danger" icon="el-icon-delete" size="min" style="float: right;" @click="deleteCart(item.goodsId)" />
          </el-card>
          <el-card v-if="count != 0 ">
            总价: {{ priceSum.toFixed (2) }}
            <el-button type="primary" style="float: right;" @click="handle">去购物车</el-button>
          </el-card>
        </el-dropdown-menu>
      </el-dropdown>
    </div>

  </div>
</template>

<script>
import goodsApi from '@/api/goodsManage'
import cartApi from '@/api/cartManage'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      goodsList: [],
      goodsName: '',
      minPrice: undefined,
      maxPrice: undefined,
      str: [],
      cartList: [],
      priceSum: 0,
      count: 0,
      detaiGoodsId: 0,
      pictureList: [
        { id: 1, url: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.DKAxt1EiFgD2LUsMETBnQgHaB7?w=314&h=91&c=7&r=0&o=5&dpr=1.4&pid=1.7' },
        { id: 2, url: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.jy0uLSlvN5BBS5wOR0KCJgHaCb?w=344&h=114&c=7&r=0&o=5&dpr=1.4&pid=1.7' },
        { id: 3, url: 'https://ts4.cn.mm.bing.net/th?id=OIP-C.RVY1cRrVApdhjrASmaViHgHaDJ&w=350&h=148&c=8&rs=1&qlt=90&o=6&dpr=1.4&pid=3.1&rm=2' },
        { id: 4, url: 'https://ts3.cn.mm.bing.net/th?id=OIP-C.NdmtB8yT0s0WXWg8JrFF9AHaDk&w=350&h=168&c=8&rs=1&qlt=90&o=6&dpr=1.4&pid=3.1&rm=2' }
      ]
    }
  },
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  created() {
    this.getAllGoods()
    this.getAllCart()
  },
  methods: {
    // 物品信息模糊查询
    getGoodsBySelect(goodsName) {
      goodsApi.getGoodsBySelect(goodsName).then(response => {
        this.goodsList = response.data
        console.log(this.goodsList)
      })
    },
    // 物品金额范围查询
    getGoodsByPrice(minPrice = 0, maxPrice = 10000) {
      if (this.goodsName !== '') {
        this.goodsList = this.goodsList.filter(item => (item.goodsPrice >= minPrice && item.goodsPrice <= maxPrice))
        console.log(this.goodsList)
      } else {
        goodsApi.getGoodsByPrice(minPrice, maxPrice).then(response => {
          this.goodsList = response.data
          console.log(this.goodsList)
        })
      }
    },
    // 物品金额倒序排列
    GoodsPriceDesc() {
      this.goodsList.sort(function(a, b) {
        return a.goodsPrice - b.goodsPrice
      })
    },
    // 物品金额升序排列
    GoodsPriceEsc() {
      this.goodsList.sort(function(a, b) {
        return b.goodsPrice - a.goodsPrice
      })
    },
    // 查询物品id
    queryGoodsId(goodsId) {
      console.log(goodsId)
      this.detaiGoodsId = goodsId
    },
    // 返回顶部
    returnTop() {
      let top = document.documentElement.scrollTop || document.body.scrollTop
      // 实现滚动效果
      const timeTop = setInterval(() => {
        document.body.scrollTop = document.documentElement.scrollTop = top -= 50
        if (top <= 0) {
          clearInterval(timeTop)
        }
      }, 10)
    },
    // 金额计算
    changebtn() {
      this.cartList.goodsCount += 1
      this.priceSum = 0
      this.count = 0
      for (let i = 0; i < this.cartList.length; i++) {
        if (this.cartList[i].goodsBuyer === this.name && this.cartList[i].goodsFlag === 0) {
          this.count += 1
          this.priceSum += this.cartList[i].goodsPrice * this.cartList[i].goodsCount
        }
      }
    },
    open() {
      const h = this.$createElement

      this.$notify({
        title: '提示小助手',
        message: h('i', { style: 'color: teal' }, '购物车空空如也~赶紧添加商品到购物车吧！')
      })
    },
    // 跳转购物车页
    handle() {
      //  路径/home对应我在router目录下index.js中定义的path属性值

      this.$router.push('/shopping/cart')
    },
    deleteCart(id) {
      cartApi.deleteCartById(id).then(response => {
        this.$message({
          type: 'success',
          message: response.message
        })
        this.getAllCart()
        this.getAllGoods()
      })
    },
    addGoodsInCart(id) {
      if (this.goodsList[id].goodsBuyer !== this.name || this.goodsList[id].goodsFlag === 0) {
        // this.$set(this.goodsList[id], '暂无', this.name)
        cartApi.deleteCartById(id).then(response => {
          this.getAllCart()
        })
      }
      cartApi.addCart(this.goodsList[id]).then(response => {
        this.$message({
          message: response.message,
          type: 'success'
        })
        console.log(this.goodsList[id])
        this.getAllGoods()
        this.getAllCart()
      })
      this.$set(this.goodsList[id], 'goodsBuyer', this.name)
      this.$set(this.goodsList[id], 'goodsMessage', '待付款')
      if (this.goodsList[id].goodsBuyer !== this.name || this.goodsList[id].goodsFlag === 0) {
        cartApi.updateCart(this.goodsList[id]).then(response => {
          this.getAllCart()
        })
      }
    },
    getAllGoods() {
      goodsApi.getAllGoods().then(response => {
        this.goodsList = response.data
      })
    },
    getAllCart() {
      cartApi.getAllCart().then(response => {
        this.cartList = response.data

        this.priceSum = 0
        this.count = 0
        for (let i = 0; i < this.cartList.length; i++) {
          if (this.cartList[i].goodsBuyer === this.name && this.cartList[i].goodsFlag === 0) {
            this.count += 1
            if (this.cartList[i].goodsCount === 0) {
              this.$set(this.cartList[i], 'goodsCount', 1)
            }
            this.priceSum += this.cartList[i].goodsPrice * this.cartList[i].goodsCount
          }
        }
      })
    }

  }
}
</script>

<style scoped>
.select{
  margin: 10px;
  width: 20%;
}

.money{
  margin: 10px;
  width: 110px;
}
.top .el-button{
  position: fixed;
  right: -5px;
  bottom: 7%;
  margin-right: 5px;
}
.kong{
  position: relative;
}
.kong .el-tag{
  position: absolute;
  right: 0;
}
.goods{
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
}

.goods img{
  width: 100%;
  height: 200px;
}
.goods .xuhao{
  margin-left: -10px;
}
.lunbo{
  width: 100%;
  height: 100%;
}
.buyitem .el-tag{
  margin-left: 15px;
}
.cart-img{
  width: 50px;
  height: 30px;
  padding-top: 15px;
}
.goods .el-card{
  position: relative;
  width: 22%;
  height: 400px;
  margin: 20px;
}
.buyitem .el-card{
  margin: 0;
}
.btn-cart{
  position: absolute;
  right: 0;
  bottom: 0;
}
.btn-exchange{
  position: absolute;
  left: -10px;
  bottom: 0;
}
.btn-buy{
  position: fixed;
  font-size: 25px;
  right: 0;
  bottom: 0;
}
.cart{
  position: relative;
}
.cart .el-dropdown{
  position: fixed;
  margin-left: 1250px;
  bottom: 50px;
}
.buyitem{
  width: 800px;
}
.btn-buy .sum{
  position: absolute;
  right: 0;
  top: 0;
  font-size: 20px;
  color: red;
}
.foot{
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
}

.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n+1) {
  background-color: #d3dce6;
}
</style>
